<template>
  <div class="home">
    <van-tabs v-model="active" animated swipeable>
      <template #nav-right>
        <div class="nav-right">
          <van-icon size="18" name="search" @click="$router.push('/search')" />
          <van-icon size="18" name="wap-nav" @click="isEditShow = true" />
        </div>
      </template>
      <van-tab v-for="item in channels" :title="item.name" :key="item.id">
        <ArticleList :channel="item" />
      </van-tab>
    </van-tabs>
    <!-- 编辑频道弹层 -->
    <van-popup
      closeable
      v-model="isEditShow"
      position="left"
      :style="{ height: '100%' }"
    >
      <EditChannels
        :channels="channels"
        :active="active"
        @changeChannels="changeChannels"
        @delCahnnels="delCahnnels"
        @addChannel="addChannel"
      />
    </van-popup>
  </div>
</template>

<script>
import EditChannels from './components/edit-channels.vue'
import ArticleList from './components/article-list.vue'
import { getUserChannels, delChannels } from '@/api/channels'
import { setChannel, getChannel } from '@/utils/storage'
export default {
  name: 'HomeIndex',
  data () {
    return {
      channels: [],
      isEditShow: false,
      active: 0
    }
  },
  components: {
    ArticleList,
    EditChannels
  },
  created () {
    this.getUserChannels()
  },
  methods: {
    // 获取频道
    async getUserChannels () {
      if (this.$store.state.tokens.token) {
        // 已登录
        const { data } = await getUserChannels()
        this.channels = data.channels
      } else {
        // 未登录
        if (getChannel()) {
          this.channels = getChannel()
        } else {
          const { data } = await getUserChannels()
          this.channels = data.channels
        }
      }
    },
    // 频道切换
    changeChannels (i) {
      this.active = i
      this.isEditShow = false
    },
    // 删除频道
    async delCahnnels (item, i) {
      if (i === 0) {
        return
      }
      if (this.active >= i) {
        this.active--
      }
      this.channels = this.channels.filter((key) => key.id !== item.id)
      if (this.$store.state.tokens.token) {
        // 已登录删除频道
        try {
          await delChannels(item.id)
          this.$toast.success('删除成功')
        } catch (err) {
          this.$toast.fail('删除失败')
        }
      } else {
        // 未登录删除频道
        setChannel(this.channels)
      }
    },
    addChannel (item) {
      this.channels.push(item)
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  .nav-right {
    position: fixed;
    right: 0;
    top: 0;
    width: 50px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    background-color: #fff;
    opacity: 0.95;
  }
}
</style>
